package com.zjp.mg.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.github.javafaker.Faker;
import com.mongodb.client.result.UpdateResult;
import com.zjp.mg.core.AjaxResult;
import com.zjp.mg.model.CommonPage;
import com.zjp.mg.model.User;
import com.zjp.mg.model.UserQuery;
import com.zjp.mg.service.UserMgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@RestController
@RequestMapping("/user")

public class UserController {
    @Autowired
    UserMgService userMgService;

    @GetMapping("list")
    public AjaxResult list(UserQuery query) {
        PageRequest of = PageRequest.of(query.getPage() - 1, query.getPageSize());
        return AjaxResult.success(CommonPage.restPage(userMgService.page(userMgService.initPageQuery(query), of)));
    }


    @GetMapping("info/{id}")
    public AjaxResult info(@PathVariable Long id) {
        return AjaxResult.success(userMgService.findById(id));
    }


    @PutMapping
    public AjaxResult update(@Validated @RequestBody User user) {
        UpdateResult updateResult = userMgService.updateById(user);
        System.out.println("updateResult = " + updateResult);
        Assert.isTrue(updateResult.getModifiedCount() == 1L, "修改用户信息失败");
        return AjaxResult.success(userMgService.findById(user.getUserId()));
    }

    @PutMapping("batchUpdate")
    public AjaxResult batchUpdate() {
        userMgService.batchUpdate();

        return AjaxResult.success();
    }

    @PostMapping("install")
    public AjaxResult install() {
        Faker faker = Faker.instance(Locale.CHINA);
        for (int i = 0; i < 5; i++) {
            User user = new User(faker.name().name(),
                    faker.university().name(), RandomUtil.randomInt(90),
                    DateUtil.offsetMillisecond(DateUtil.date(), RandomUtil.randomInt()));
            int randomInt = RandomUtil.randomInt(1, 6);
            List<String> cityList = new ArrayList<>();
            for (int j = 0; j < randomInt; j++) {
                cityList.add(faker.address().city());
            }
            user.setCity(cityList);
            userMgService.insertByNextAutoId(user);
        }
        return AjaxResult.success();
    }
}
